clear all
*cap log close
set more off
set seed 603


foreach Y in cite_ny1 contest {

	// read data -----------------------------
	use "${temp}/data_exper", clear

	// define outcome ----------------------
	gen Y = `Y'

	// setup for heterogeneity ---------------
	gen G = hiexp 

	// use bins from binsreg -----------------
	preserve
	gen random = runiform()
	binsreg Y Z if G==1 & random<0.2 [aw=rwt], absorb(totfe) binspos(es) nbins(12) savedata(binscatter) replace
	use binscatter, clear 
	qui summ binid
	local nbins = `r(max)'
	rename lef_ep lef_
	rename rig_ep rig_ 
	rename dots_x mid_
	gen index = 1 
	keep index binid lef_ rig_ mid_
	reshape wide lef_ rig_ mid_, i(index) j(binid)
	tempfile bins
	save    `bins'
	rm binscatter.dta 
	restore 
	// -------------------------------------


	// Code bins -----------------------------
	gen index = 1 
	merge m:1 index using `bins', nogen 
	drop index 

	gen bin = .
	forval q = 1/`nbins' {
		replace bin = `q' if Z>=lef_`q' & Z<rig_`q'
	}
	replace bin = `nbins' if Z==1 

	// Create bin and bin interaction dummies -----------
	forval q = 1/`nbins' {
		gen bin_`q'    = (bin==`q')
	}
	forval q = 1/`nbins' {
		gen bin_`q'_g1 = (bin==`q')*(G==1)
	}

	// Create regression storage variables -------------
	gen binid  = _n if _n <= `nbins'
	gen mid    = . 
	gen beta_0 = 0 if _n <= `nbins'
	gen beta_1 = 0 if _n <= `nbins'

	// Estimate bin coefficients ------------------
	reghdfe Y bin_2-bin_`nbins' bin_2_g1-bin_`nbins'_g1 G [aw=rwt], absorb(totfe, savefe) nocons

	// store estimates ------------
	forval q = 1/`nbins' {
		qui summ mid_`q'
		replace mid = `r(mean)' if binid==`q'
		if `q' >= 2 {
			replace beta_0 = _b[bin_`q'] if binid == `q'
			replace beta_1 = _b[bin_`q'] + _b[bin_`q'_g1] if binid == `q'
		}
	}

	// add back in fe + intercept term ---------
	local intercept = _b[G]
	qui summ __hdfe1 if G == 0 
	local mufe0 = `r(mean)'
	qui summ __hdfe1 if G == 1 [aw=rwt]
	local mufe1 = `r(mean)'

	replace beta_0 = beta_0 + `mufe0' 
	replace beta_1 = beta_1 + `mufe1' + `intercept'

	// store output ---------
	keep if !mi(binid)
	keep binid mid beta_0 beta_1
	gen Y = "`Y'"

	if "`Y'" == "cite_ny1" {
		save "${temp}/exper_binscatter", replace
	} 
	else {
		qui append using "${temp}/exper_binscatter"
		save "${temp}/exper_binscatter", replace
	}

}




// Fix output to mimic binsreg output ----------------
local k = 1
foreach Y in cite_ny1 contest {
	forval G=0/1 {
		use "${temp}/exper_binscatter", clear 
		keep if Y == "`Y'"
		keep Y binid mid beta_`G'
		rename Y yvar
		rename binid dots_binid
		rename mid dots_x  
		rename beta_`G' dots_fit 
		gen g = `G'
		order yvar g dots_binid dots_x dots_fit 
		tempfile temp`k'
		save    `temp`k''
		local ++k
	}
}


use `temp1', clear
forval j = 2/4 {
	qui append using `temp`j''
}
save "${temp}/exper_binscatter", replace 








